use sqlx::{query, sqlite::SqliteQueryResult, FromRow};

use super::{user::{User, UserVoForAdd}, Connection };


#[tauri::command]
pub(crate) async fn get_user()->Result<Vec<User>,String>{

    let a = Connection::get_instance().await;
    let conn_opt = a.clone();
    let conn = conn_opt.get_sqlite_pool().as_ref();
    let result = query("select * from user").fetch_all(conn.unwrap()).await;
    // println!("{:?}",result);
    if let Ok(rows) = result{
        let result = rows.iter().map(|row|{
            User::from_row(row).unwrap()
        }).collect();
         Ok(result)
    }else{
        return Err("查询失败".to_string());
    }

}


#[tauri::command]
pub(crate) async fn add_user(userInfo:UserVoForAdd) -> Result<String, String> {
    
    let a = Connection::get_instance().await;
    let conn_opt = a.clone();
    let conn = conn_opt.get_sqlite_pool().as_ref();
    let result = sqlx::query(
        "insert into user(name,age,address) values(?,?,?)")
    .bind(userInfo.get_name())
    .bind(userInfo.get_age())
    .bind(userInfo.get_address())
    .execute(conn.unwrap()).await;
    if let Ok(_) = result{
        return Ok(String::from("添加成功"));
    }else{
        return Err("add user failed".to_string());
    }
    
}